// src/api/request.ts
import axios, { type AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import router from '../router';

const service = axios.create({
    baseURL: 'http://localhost:8081', // 后端API根地址
    timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 1. 从 localStorage 获取 token
        const token = localStorage.getItem('token');

        // 2. 如果 token 存在，就添加到请求头
        if (token) {
            // 3. 确保格式是 'Bearer ' + token (注意 'Bearer' 和 token 之间的空格)
            config.headers['Authorization'] = `Bearer ${token}`;
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data;
        if (res.token || typeof res === 'string') {
            return res;
        }
        if (res.code !== 200) {
            ElMessage({ message: res.message || 'Error', type: 'error' });
            if (res.code === 401 || res.code === 403) {
                localStorage.removeItem('token');
                router.push('/login');
            }
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res.data;
        }
    },
    error => {
        ElMessage({ message: error.response?.data?.message || error.message, type: 'error' });
        return Promise.reject(error);
    }
);

export default service;
